using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace Universe.Farm.Service.Mesages
{
    class XmlUtils
    {
        public static XmlDocument Serialize(Type t, object value)
        {
            XmlSerializer xs = new XmlSerializer(t);
            using (MemoryStream mem = new MemoryStream())
            using (StreamWriter wr = new StreamWriter(mem, Encoding.UTF8))
            {
                XmlTextWriter xw = new XmlTextWriter(wr);
                xw.Formatting = Formatting.None;
                xs.Serialize(xw, value);
                xw.Flush();

                XmlDocument ret = new XmlDocument();
                using (MemoryStream mem2 = new MemoryStream(mem.ToArray()))
                using (StreamReader wr2 = new StreamReader(mem2, Encoding.UTF8))
                {
                    XmlTextReader xr = new XmlTextReader(wr2);
                    ret.Load(xr);
                    return ret;
                }
            }
        }

        public static byte[] Serialize(XmlDocument doc)
        {
            using (MemoryStream dmem = new MemoryStream())
            using (StreamWriter wrd = new StreamWriter(dmem, Encoding.UTF8))
            {
                XmlTextWriter xwr1 = new XmlTextWriter(wrd);
                xwr1.Formatting = Formatting.None;
                doc.Save(xwr1);
                wrd.Flush();
                xwr1.Flush();
                return dmem.ToArray();
            }
        }

        public static XmlDocument ParseXmlDocument(byte[] description)
        {
            using (MemoryStream dmem = new MemoryStream(description))
            using (StreamReader rd = new StreamReader(dmem, Encoding.UTF8))
            {
                XmlTextReader xrd = new XmlTextReader(rd);
                XmlDocument doc = new XmlDocument();
                doc.Load(xrd);
                return doc;
            }
        }

        public static byte[] Serialize(XmlElement el)
        {
            using (MemoryStream dmem = new MemoryStream())
            using (StreamWriter wrd = new StreamWriter(dmem, Encoding.UTF8))
            {
                XmlTextWriter xwr1 = new XmlTextWriter(wrd);
                xwr1.Formatting = Formatting.None;
                el.WriteTo(xwr1);
                wrd.Flush();
                xwr1.Flush();
                return dmem.ToArray();
            }
        }

        public static XmlElement ParseXmlElement(byte[] parameters)
        {
            using (MemoryStream dmem = new MemoryStream(parameters))
            using (StreamReader rd = new StreamReader(dmem, Encoding.UTF8))
            {
                XmlTextReader xrd = new XmlTextReader(rd);
                XmlDocument doc = new XmlDocument();
                doc.Load(xrd);
                return doc.DocumentElement;
            }
        }
    }
}